package com.polaris.live.dialog_fragment

import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.gyf.immersionbar.ImmersionBar
import com.polaris.live.R
import com.polaris.live.adapter.GiveFollowerAdapter
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.databinding.PopupGiveUserBinding
import com.polaris.live.im.sfs.bean.live.ext.UserBasicVo
import com.polaris.live.interface_bag.TextWatcherAdapter
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.ui.message.fragment.dialog.BottomDialogFragment
import com.polaris.live.utils.fragment.FragmentUtils
import com.polaris.live.viewmodel.GiveViewModel
import com.polaris.live.widget.refresh.ListOperator
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 赠送礼物弹窗
 *
 * @author Created by 天晴 on 2024/7/18/009 11:12
 */
class GiveFragmentDialog : BottomDialogFragment() {

    private lateinit var mBinding: PopupGiveUserBinding

    private val mViewModel by viewModels<GiveViewModel>()

    override val isReusable: Boolean = false

    private var mListOperator: ListOperator<UserBasicVo>? = null

    private var callback: ((userBasicResp: UserBasicVo) -> Unit)? = null
    fun setUserCallback(l: (userBasicResp: UserBasicVo) -> Unit) {
        callback = l
    }

    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .transparentBar()
            .navigationBarDarkIcon(false)
            .init()
    }

    override fun setStyle() {
        setStyle(STYLE_NO_FRAME, R.style.DialogFragmentBottomGiftDialog)
    }

    override fun getDialogHeight(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        return PopupGiveUserBinding.inflate(inflater, container, false).let {
            mBinding = it
            it.root
        }
    }

    private val mAdapter by lazy { GiveFollowerAdapter() }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.recyclerView.setEnableRefresh(false)
        mBinding.recyclerView.setEmptyTip(
            R.drawable.family_empty,
            getString(com.polaris.live.translation.R.string.no_focus)
        )
        mBinding.recyclerView.apply {
            recycler.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            recycler.itemAnimator = null
            mListOperator = attachedAdapter(mAdapter, mViewModel)
            mListOperator?.observe(
                this@GiveFragmentDialog,
                mViewModel.followersLiveData
            )
        }
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.give_tv -> {
                    callback?.invoke(mAdapter.getItem(position))
                }
            }
        }
        initListener()
        mViewModel.onRefresh()
    }

    private var searchJob: Job? = null
    private fun initListener() {
        mBinding.searchEdit.addTextChangedListener(object : TextWatcherAdapter() {
            override fun afterTextChanged(s: Editable?) {
                super.afterTextChanged(s)
                val searchString = mBinding.searchEdit.text.toString()
                if (searchString.isEmpty()) {
                    mListOperator?.resetData()
                    mViewModel.searchAgency(null)
                    searchJob?.cancel()
                    searchJob = null
                } else {
                    searchJob?.cancel()
                    searchJob = mViewModel.viewModelScope.launch {
                        try {
                            delay(500)  // 延迟500
                            mViewModel.searchAgency(searchString)
                        } finally {
                            if (searchJob == coroutineContext[Job]) {
                                searchJob = null
                            }
                        }
                    }
                }
            }
        })

        mBinding.editClear.setOnSingleClickListener {
            mBinding.searchEdit.text = Editable.Factory.getInstance().newEditable("")
        }
        mBinding.mainLl.setOnSingleClickListener {
        }
        mBinding.framelayout.setOnSingleClickListener {
            hide()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        searchJob?.cancel()
        searchJob = null
    }

    fun setCallback(callback: ((userBasicResp: UserBasicVo) -> Unit)) {
        this.callback = callback
    }

    companion object {

        fun show(context: Context, callback: (GiveFragmentDialog.(userBasicResp: UserBasicVo) -> Unit)) {
            GlobalPopupManager.showCompletePopup(context, isOk = {
                val fragmentManager = FragmentUtils.getFragmentManager(context)
                    ?: return@showCompletePopup
                GiveFragmentDialog().apply {
                    setCallback {
                        callback.invoke(this, it)
                    }
                }.show(fragmentManager, "GiveFragmentDialog")
            })

        }

    }
}

